<template>
  <div>
    <el-dialog
      :model-value="props.dialogVisible"
      :title="props.formStatus === 1 ? '编辑项目' : '新增项目'"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <el-form ref="projectFormRef" :model="projectForm" :rules="projectFormRules" label-width="120px" @submit.prevent>
        <el-form-item label="项目名称：" prop="projectName">
          <el-input v-model="projectForm.projectName" clearable placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="项目排序：" prop="projectOrder">
          <el-input v-model="projectForm.projectOrder" clearable placeholder="请输入项目排序"></el-input>
        </el-form-item>
        <el-form-item label="父级项目：" prop="parentId">
          <el-tree-select
            v-model="projectForm.parentId"
            :data="treeData"
            check-strictly
            node-key="pid"
            :props="defaultProps"
            :expand-on-click-node="false"
            :disabled="treeSelectDisabled"
            highlight-current
            clearable
            placeholder="请选择父级项目"
            style="width: 100%;"
            @node-click="handleTreeSelectClick"/>
        </el-form-item>
        <el-form-item label="项目地址：" prop="projectAddr">
          <el-input v-model="projectForm.projectAddr" clearable placeholder="请输入项目地址"></el-input>
        </el-form-item>
        <el-form-item label="代理商：" prop="agencyId">
          <el-select v-model="projectForm.agencyId" clearable placeholder="请选择代理商" style="width: 100%;">
            <el-option
              v-for="item in agencyOptions"
              :key="item.agencyId"
              :label="item.agencyName"
              :value="item.agencyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="代理人：" prop="agentName">
          <el-input v-model="projectForm.agentName" clearable placeholder="请输入代理人"></el-input>
        </el-form-item>
        <el-form-item label="代理联系电话：" prop="agentPhoneNo">
          <el-input v-model="projectForm.agentPhoneNo" clearable placeholder="请输入代理联系电话"></el-input>
        </el-form-item>
        <el-form-item label="客户名称：" prop="customerName">
          <el-input v-model="projectForm.customerName" clearable placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item label="客户联系电话：" prop="customerPhoneNo">
          <el-input v-model="projectForm.customerPhoneNo" clearable placeholder="请输入客户联系电话"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit(projectFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ProjectModifyForm">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { projectList, projectInsert, projectUpdate } from '@/api/project-manage'
import { agencyList } from '@/api/system-params'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formStatus: {
    type: Number,
    default: 0
  },
  formData: {
    type: Object,
    default: {}
  }
})

const agencyOptions = ref<any>([])
const defaultProps = {
  label: 'projectName',
  children: 'projectTree',
}
const treeData = ref<any>([])
const projectForm = reactive({
  pid: -1,
  level: 0,
  projectName: '',
  projectOrder: '',
  parentId: '',
  projectAddr: '',
  agencyId: '',
  agentName: '',
  agentPhoneNo: '',
  customerName: '',
  customerPhoneNo: ''
})
const projectFormRef = ref<FormInstance>()
const projectFormRules = reactive<FormRules>({
  projectName: [
    { required: true, message: '请输入项目名称！' }
  ],
  projectOrder: [
    { required: true, message: '请输入项目排序！' }
  ],
  parentId: [
    { required: true, message: '请选择父级项目！' }
  ],
})
const treeSelectDisabled = ref(false)

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    getProjectData()
    getAgencyListData()
    if (props.formStatus === 1) {
      projectForm.pid = props.formData.pid
      projectForm.level = props.formData.level
      projectForm.projectName = props.formData.projectName
      projectForm.projectOrder = props.formData.projectOrder
      projectForm.parentId = props.formData.parentId
      projectForm.projectAddr = props.formData.projectAddr
      projectForm.agencyId = props.formData.agencyId
      projectForm.agentName = props.formData.agentName
      projectForm.agentPhoneNo = props.formData.agentPhoneNo
      projectForm.customerName = props.formData.customerName
      projectForm.customerPhoneNo = props.formData.customerPhoneNo
      treeSelectDisabled.value = true
    } else {
      treeSelectDisabled.value = false
      if (props.formData.parentId) {
        projectForm.parentId = props.formData.pid
        projectForm.level = props.formData.level
        treeSelectDisabled.value = true
      }
    }
  }
})

// 获取选中层级
const handleTreeSelectClick = (row: any) => {
  projectForm.level = row.level
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  resetForm(projectFormRef.value)
  proxy?.$emit('update:dialogVisible', false)
}

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      if (props.formStatus === 0) {
        let { pid, ...params } = projectForm
        params.level += 1
        await projectInsert(params).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success(`新增成功！`)
            emit('submit')
            handleClose()
          } else {
            ElMessage.error(`${res.msg}`)
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        let params = Object.assign({}, projectForm)
        await projectUpdate(params).then((res: any) => {
          if (res.code === 0) {
            ElMessage.success(`编辑成功！`)
            emit('submit')
            handleClose()
          } else {
            ElMessage.error(`${res.msg}`)
          }
        }).catch(err => {
          console.log(err)
        })
      }
    }
  })
}

// 获取代理商下拉数据
const getAgencyListData = async () => {
  await agencyList().then((res: any) => {
    if (res.code === 0) {
      agencyOptions.value = [...res.list]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}

// 获取项目树表格数据
const getProjectData = async () => {
  await projectList().then((res: any) => {
    if (res.code === 0) {
      treeData.value = [res.data]
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>

</style>
